<template>
  <div class="box_list">
    <!-- 路径面包屑区域 -->
    <el-breadcrumb class="mb15">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 工作区域 -->
    <div class="box_content">
      <el-card>
        <!-- 查询区域 -->
        <el-row :gutter="15">
          <el-col :span="5">
            <el-input
              placeholder="请输入内容"
              size="small"
              v-model="userInfo.query"
              clearable
              @clear="getUserList"
            >
              <el-button slot="append" size="small" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="addForm()">新增</el-button>
          </el-col>
        </el-row>

        <!-- table 列表区域 -->
        <el-table border stripe :data="usersList" class="mt15">
          <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色" align="center"></el-table-column>
          <el-table-column prop="mg_state" label="状态" width="180" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300" align="center">
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editForm(scope.row.id)"
              >修改</el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deletUser(scope.row.id)"
              >删除</el-button>
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="rolesSetting(scope.row)"
              >分配角色</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- table 分页功能 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="userInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="userInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </el-card>
    </div>

    <!-- -------------------新增form表单-------------------- -->
     <AddForm ref="childrenRef" @refreshData="refreshMethod"></AddForm>
  
    <!-- -------------------修改form表单-------------------- -->
    <EditForm ref="editChildrenRef" :editUserForm="editUserForm" @refreshMethod="refreshMethod"></EditForm>

    <!-- -------------------分配角色-------------------- -->
     <RolesSetting ref="rolesSettingRef" :userData="userData" :rolesList="rolesList" @refreshData="refreshMethod"></RolesSetting>

  </div>
</template>

<script>
import AddForm from "./AddForm";
import EditForm from "./EditForm";
import RolesSetting from "./RolesSetting";
export default {
  components: { RolesSetting, AddForm ,EditForm},
  data() {
    return {
      userInfo: {
        query: "",
        // 当前页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5,
      },
      usersList: [],
      total: 0,

      // *************************修改form表单的data*****************
      editUserForm: {},
      // *********************************分配角色**********************
      rolesVisible: false,
      //当前用户信息对象
      userData: {},
      //所有角色信息数组
      rolesList: [],
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 获取用户列表数据
    getUserList() {
      this.$axios
        .get("users", { params: this.userInfo })
        .then((res) => {
          // then用于处于成功事件，res为服务端返回的数据
          let usersData = res.data;
          // console.log(usersData);
          if (usersData.meta.status == 200) {
            // console.log("获取菜单成功");
            this.usersList = usersData.data.users;
            this.total = usersData.data.total;
          } else {
            // console.log("获取菜单失败");
            this.$message.error(usersData.meta.msg);
            return;
          }
        })
        .catch((error) => {
          console.log(error); // cathch用于处理错误事件
        });
    },
    //监听pagesize改变，每页显示多少条数据改变
    handleSizeChange(newSize) {
      //console.log(newSize);
      this.userInfo.pagesize = newSize;
      this.getUserList();
      
    },
    //监听页码值改变
    handleCurrentChange(newPage) {
      //console.log(newPage);
      this.userInfo.pagenum = newPage;
      this.getUserList();
    },
    //监听switch 开关状态变化 userState这个就收参数随便取的
    userStateChange(userState) {
      //console.log(userState)
      this.$axios
        .put(`users/${userState.id}/state/${userState.mg_state}`)
        .then((res) => {
          // console.log(res)
          if (res.data.meta.status == 200) {
            this.$message.success("更新用户状态成功！");
          } else {
            this.$message.error("更新用户状态失败！");
            userState.mg_state = !userState.mg_state;
          }
        })
        .catch((error) => {
          console.log(error); // cathch用于处理错误事件
        });
    },
    // 删除当前用户
    deletUser(id) {
      this.$msgBox
        .confirm("此操作将永久删除该用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then((res) => {
          this.$axios
            .delete("users/" + id)
            .then((res) => {
              // console.log(res)
              if (res.data.meta.status == 200) {
                this.$message.success("删除当前用户成功");
                this.getUserList();
              } else {
                return this.$message.error("删除当前用户失败");
              }
            })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 接收子组件发送请求数据刷新当前列表
    refreshMethod(){
       this.getUserList();
    },
    // *************************新增form表单的js*****************
    // 点击新增用户form
    addForm(){
      this.$refs.childrenRef.showDialog();
    },
    // ************************修改form表单的js*****************
    //点击修改用户form
    editForm(id) {
      this.$axios
        .get("users/" + id)
        .then((res) => {
          if (res.data.meta.status == 200) {
            this.$message.success("获取当前用户成功");
            this.editUserForm = res.data.data;
          } else {
            this.$message.error("获取当前用户失败");
          }
        })
        .catch((error) => {
          this.$message.error("请求发生异常");
          return;
        });
        this.$refs.editChildrenRef.showDialog();
    },
    // *****************************分配权限***********************
    //分配角色
    rolesSetting(userData) {
      // 当前用户信息
      this.userData = userData;
      // 所有角色信息
      this.$axios
        .get("roles")
        .then((res) => {
          if (res.data.meta.status == 200) {
            this.rolesList = res.data.data;
          } else {
            this.$message.error("获取角色失败");
          }
        })
        .catch((error) => {
          console.log(error); //cathch用于处理错误事件
        });
      this.$refs.rolesSettingRef.showDialog();
    },
  },
};
</script>

<style scoped>
</style>